import "../css/Sidebar.css";
import SubSibar from "./common/comps/subSideBar"
import useForm from "@module/useForm";
import Table from "@ui/RJMart/table";
import "@ui/RJMart/table/table.css";
import CookieUtils from "pages/ruijing/common/utils/CookieUtils";
import YanKeSelectCard from "@root/P/components/YankeSelectCard";
import ZenModal from "@root/components/zenUi/ZenModal/ZenModal";
import SubjectInfo from "pages/ruijing/Statements/components/SubjectInfo";
import AddDeptForm from "pages/ruijing/Statements/components/AddDept";
function systemSet(props) {

    //初始化插件入参
    const {} = props;
    const tabNames = ["收货地址标签管理"];
    const tabPermission = ["采购单查看"]; //自测临时权限，应为地址标签管理
    const sideBarName = "系统管理";
    const permissions = JSON.parse(localStorage.getItem("STORE_USERPERMISSION"));
    const orgId = CookieUtils.getCookie("orgId");
    const showGroup = [true];
    const selectedGroup = [true];

    //收货地址标签管理表头
    const logisticLabelListCol = [
        {
            key:"labelName",
            title:"地址标签名称"
        },
        {
            key:"rank",
            title:"排序",
        },
        {
            key:"operation",
            title:"操作",
            render:item =>{
                return(
                <div>
                    <a onClick={(e) =>{editLabel(item.id,item.orgId,item.labelName,item.rank)}} className="zen_m-r-30 zen_cur-p">编辑</a>
                    <a onClick={(e) =>{deleteLabel(item.id)}} className="zen_cur-p">删除</a>
                </div>
                )
            }
        }
    ]

    //初始化插件状态值及状态更新方法
    const [systemSetStatus, updateSystemSetStatus] = usePartState({
        moduleHeader:"",
        logisticListOutput:[],
        logisticListInput:{
            orgId:parseInt(orgId),
            rankType:1
        }
    })

    //更新视图数据 私有的方法前缀用_
    function _updateData(value) {
        let newValue = { ...systemSetStatus, ...value };
        updateSystemSetStatus(newValue);
    }

    //更新视图数据方法外部接口
    function updateFunctions(params1){
        _updateData(
            (systemSetStatus.status1 = tabNames[0])
        )
    }

    function editLabel(id,orgId,label,rank) {
        let editInput = {
            "id": id,
            "orgId": orgId,
            "labelName": label,
            "rank": rank
        }
        showDialog(editInput);
    }

    function deleteLabel(id) {
        let url = "/store/api/hms/delivery/address/label/delete";
        let deleteInput = {
            id:id
        }
        REST.post(url,deleteInput).then(
            data => {
                if (data.msg == "success"||data.code=="200") {
                    if(data.success){
                        ZenUI.ST("收货地址标签删除成功", 2);
                        //getLogisticList(systemSetStatus.logisticListInput);
                        window.location.reload();
                    }else{
                        ZenUI.ST("收货地址标签删除失败", 2);
                    }
                }else{
                    ZenUI.ST(data.message, 2);
                }
            },
            error => {}
        );
    }

    //设置收货标签
    function setLabel(inputData){
        let url = "/store/api/hms/delivery/address/label/saveOrUpdate";
        REST.post(url,inputData).then(
            data => {
                if (data.msg == "success"||data.code=="200") {
                   if(data.success){
                       ZenUI.ST("收货地址标签设置成功", 2);
                       getLogisticList(systemSetStatus.logisticListInput);
                   }else{
                       ZenUI.ST("收货地址标签设置失败", 2);
                   }
                }else{
                    ZenUI.ST(data.message, 2);
                }
            },
            error => {}
        );
    }
    
    function showDialog(inputdata) {
        let modal = null;
        function closeModal(value) {
            modal.hide();
        }
        function Content(props) {
            props.item.passParams && props.item.passParams("abc");
            props.item.changeDep = SubjectInfo.changeDep;
            props.item.getDeptsW = SubjectInfo.getDeptsW2;
            props.item.info = inputdata;
            return labelInfoForm(props);
            //return ""
        }

        function labelInfoForm(props) {

            //定义全局变量 const [scope值，更新方法] = React.useState({初始化的值});
            const [formStatus, updateFormStatus] = React.useState({
                errorReason: "",
                submitStatus:0,
                labelRank: props.item.info.hasOwnProperty("rank")?props.item.info.rank:"",
                labelName:props.item.info.hasOwnProperty("labelName")?props.item.info.labelName:"",
                labelId:props.item.info.hasOwnProperty("id")?props.item.info.id:""
            });

            //定义表单 useForm（回调，默认值，表单名）
            const { formData, handleChange, handleSubmit,updateFormData, validations, addValidate, addValidateMulti } = useForm(
                doSubmit,
                {name:formStatus.labelName,rank:formStatus.labelRank},
                "labelInfoForm"
            );

            function beforeHandleChange(event) {
                _updateData((formStatus.errorReason = ""))
                handleChange(event);
            }

            //更新视图数据 私有的方法前缀用_
            function _updateData(value) {
                let newValue = { ...formStatus, ...value };
                updateFormStatus(newValue);
            }

            React.useEffect(() => {
                console.log("refresh view");
            },[]);

            //提交事件
            function doSubmit() {
                let submitUrl = "/store/api/hms/delivery/address/label/saveOrUpdate";
                let submitData ={
                    "orgId": parseInt(orgId),
                    "labelName": formData.name,
                    "rank": parseInt(formData.rank)
                }
                if(formStatus.labelId!=""){
                    submitData.id = formStatus.labelId
                }
                REST.post(submitUrl, submitData, "noInfo").then(
                    (data) =>{
                        if(data.code == "200"){
                            window.location.reload();
                        }else{
                            ZenUI.ST(data.msg, 2);
                        }
                    }
                )
            }

            function validate1(value){
                let pattern = /^[\u4e00-\u9fa5]+$/;
                if(value==""||value==null||value==undefined){
                    _updateData(
                        (formStatus.submitStatus = 1)
                    );
                    return "请填写地址标签名称";
                }else{
                    if(!pattern.test(value)) {
                        _updateData(
                            (formStatus.submitStatus = 1)
                        );
                        return "地址标签名称不能超过12个汉字"
                    }else if(value.length>12){
                        _updateData(
                            (formStatus.submitStatus = 1)
                        );
                        return "地址标签名称不能超过12个汉字"
                    }else{
                        _updateData(
                            (formStatus.submitStatus = 0)
                        );
                        return ""
                    }
                }
            }

            function validate2(value){
                let pattern = /^[0-9]*[1-9][0-9]*$/;
                if(value==""||value==null||value==undefined){
                    _updateData(
                        (formStatus.submitStatus = 1)
                    );
                    return "请填写标签顺序";
                }else{
                    if(!pattern.test(value)) {
                        _updateData(
                            (formStatus.submitStatus = 1)
                        );
                        return "请输入正整数"
                    }else{
                        _updateData(
                            (formStatus.submitStatus = 0)
                        );
                        return ""
                    }
                }
            }

            addValidateMulti({name:[validate1],rank:[validate2]});

            return(
                <div>
                    <form
                        name="labelInfoForm"
                        className="zen_t-70 zen_r-0 zen_z-i-99 zen_bdr-8 zen_fs-14 zen_m-t-10"
                        onSubmit={handleSubmit}
                    >
                        <div className={"zen_m-b-30"}>
                            <div className="zen_il-bl zen_w-100 zen_t-r"><span className="zen_F5222D zen_m-2">*</span>地址标签名称</div>
                            <input
                                className={(!formData.$$status.hasOwnProperty("name"))||formData.$$status.name==""?"zen_w-240 zen_h-32 zen_l-h-32 zen_p-h-25 zen_bd-D1D1D1 zen_m-l-10 zen_bdr-5 zen_fs-12":"zen_w-240 zen_h-32 zen_l-h-32 zen_p-h-25 zen_bd-red zen_m-l-10 zen_bdr-5 zen_fs-12"}
                                name="name"
                                type="text"
                                value={formData.name}
                                onChange={beforeHandleChange}
                                placeholder={"地址标签名称不超过12个汉字"}
                                required
                            />
                            <br />
                            <div className="zen_red zen_m-l-130 zen_m-t-10">{formData.$$status.name}</div>
                        </div>
                        <div className={"zen_m-b-30"}>
                            <div className="zen_il-bl zen_w-100 zen_t-r"><span className="zen_F5222D zen_m-2">*</span>排序顺序</div>
                            <input
                                className={(!formData.$$status.hasOwnProperty("rank"))||formData.$$status.rank==""?"zen_w-240 zen_h-32 zen_l-h-32 zen_p-h-25 zen_bd-D1D1D1 zen_m-l-10 zen_bdr-5 zen_fs-12":"zen_w-240 zen_h-32 zen_l-h-32 zen_p-h-25 zen_bd-red zen_m-l-10 zen_bdr-5 zen_fs-12"}
                                name="rank"
                                type="text"
                                value={formData.rank}
                                onChange={beforeHandleChange}
                                placeholder={"请输入正整数，数字越小，排序越前"}
                                required
                            />
                            <br />
                            <div className="zen_red zen_m-l-130 zen_m-t-10">{formData.$$status.rank}</div>
                        </div>
                        <div className="zen_t-c">
                            <button type="submit" className={formStatus.submitStatus==0?"h-button-primary h-modal-conBtn h-button-button":"h-button-button h-button-primary h-button-disabled"} disabled={formStatus.submitStatus==0?false:true}>
                                确认
                            </button>
                            <div onClick={props.item.close} className="h-button-button h-button-sub h-modal-canBtn">
                                取消
                            </div>
                        </div>
                    </form>
                </div>
            )
        }
        let options = {
            header: inputdata.hasOwnProperty("id")&&inputdata.id!=undefined
                    ? "编辑收货地址标签"
                    : "新增收货地址标签",
            content: Content,
            size: "sm",
            close: closeModal,
            hideFooter:true
        };
        modal = ZenModal.loadModal(options);
        modal.show();
    }

    //收货标签列表
    function getLogisticList(inputData){
        let url = "/store/api/hms/delivery/address/label/list";
        REST.post(url,inputData).then(
            data => {
                if (data.message == "success"||data.code=="200") {
                    let outputData = [];
                    data.data.map((item,index) =>{
                        let tempItem = JSON.parse(JSON.stringify(item));
                        tempItem.operation = JSON.parse(JSON.stringify(item));
                        outputData.push(tempItem);
                    })
                    _updateData(
                        (systemSetStatus.logisticListOutput = outputData)
                    )
                }else{
                    ZenUI.ST(data.message, 2);
                }
            },
            error => {}
        );
    }

    //componentOnMount
    React.useEffect(() => {
        console.log("refresh view");
        getLogisticList(systemSetStatus.logisticListInput);
        _updateData(
            (systemSetStatus.moduleHeader = tabNames[0])
        )
    },[]);

    return (
        <div>
            <SubSibar
                tabNames={tabNames}
                tabPermission={tabPermission}
                sideBarName={sideBarName}
                permissions={permissions}
                showGroup={showGroup}
                selectedGroup={selectedGroup}
            />
            <div className="zen_w-p80 zen_il-bl">
                <div className="zen_il-bl zen_m-30 zen_fs-16 zen_t-l zen_p-b-5 zen_m-b-15 zen_w-p100" style={{borderBottom: "1px solid #ccc"}}>
                    <div className="zen_fs-16" style={{borderLeft: "3px solid #13b5bd",padding: "5px 10px"}}>{systemSetStatus.moduleHeader}</div>
                </div>

                <br />
                <div className="zen_il-bl zen_fs-14 zen_t-l zen_p-b-5" style={{width:"100%"}}>
                    <div className="zen_il-bl zen_f-left zen_FFFFFF zen_bg-13b5bd zen_m-l-30" style={{padding:"10px 30px"}} onClick={(e) =>{showDialog({})}}>新增标签</div>
                </div>

                <div className="zen_p-t-15" style={{width:"100%",padding:"30px"}}>
                    {systemSetStatus.logisticListOutput.length>0?<Table
                    columns={logisticLabelListCol}
                    data={JSON.parse(JSON.stringify(systemSetStatus.logisticListOutput))}
                    bordered
                />:""}
                </div>
            </div>

        </div>
    )
}

export default systemSet;